package com.heima.admin.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.admin.mapper.AdUsermapper;
import com.heima.admin.service.AdUserService;
import com.heima.common.exception.CustException;

import com.heima.model.admin.pojos.AdUser;
import com.heima.model.common.dtos.AdUserDTO;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.admin.vos.AdUserVo;
import com.heima.utils.common.AppJwtUtil;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.util.Date;
import java.util.HashMap;

@Service
public class AdUserServiceImpl extends ServiceImpl<AdUsermapper, AdUser> implements AdUserService {
    @Override
    public ResponseResult login(AdUserDTO dto) {
//1.校验参数(name password)
        if (StringUtils.isBlank(dto.getName()) || StringUtils.isBlank(dto.getPassword())) {
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID, "参数错误");
        }

        //2。根据用户名查询用户信息
        AdUser adUser = getOne(Wrappers.<AdUser>lambdaQuery().eq(AdUser::getName, dto.getName()));
        if (adUser == null) {
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST, "用户名不存在");
        }
//3。看密码是否和数据库一致

        String dbPwd = dto.getPassword();  //获取用户输入密码
        String salt = adUser.getSalt();    //获取盐


        String newPwd = DigestUtils.md5DigestAsHex((dbPwd + salt).getBytes());
        if (!newPwd.equals(adUser.getPassword())) {
            CustException.cust(AppHttpCodeEnum.LOGIN_PASSWORD_ERROR);
        }

        //4。看用户状态status  0    9
        //4。1无效
        if (adUser.getStatus().intValue() != 9) {
            CustException.cust(AppHttpCodeEnum.LOGIN_STATUS_ERROR);
        }

        //5。修改登录时间
        adUser.setLoginTime(new Date());
        updateById(adUser);
        //6。颁发token
        String token = AppJwtUtil.getToken(adUser.getId().longValue());
        //7。返回结果
        AdUserVo userVo = new AdUserVo();
        BeanUtils.copyProperties(adUser, userVo);

        HashMap result = new HashMap<>();
        result.put("token", token);
        result.put("user", userVo);
        return ResponseResult.okResult(result);
    }
}
